package org.jeecg.modules.carinfo.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.Data;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.basicGoods.entity.BasicGoods;
import org.jeecg.modules.basicGoods.service.IBasicGoodsService;
import org.jeecg.modules.carinfo.entity.CarRecord;
import org.jeecg.modules.carinfo.entity.CarRegister;
import org.jeecg.modules.carinfo.service.ICarRecordService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.carinfo.service.ICarRegisterService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 出入场查询
 * @Author: jeecg-boot
 * @Date: 2023-12-04
 * @Version: V1.0
 */
@Api(tags = "出入场查询")
@RestController
@RequestMapping("/carinfo/carRecord")
@Slf4j
public class CarRecordController extends JeecgController<CarRecord, ICarRecordService> {
    @Autowired
    private ICarRecordService carRecordService;
    @Autowired
    private ICarRegisterService carRegisterService;
    @Autowired
    private IBasicGoodsService basicGoodsService;
    @Autowired
    private RedisUtil redisUtil;

    @Value("${jeecg.path.upload}")
    private String upLoadPath;


    /**
     * 分页列表查询
     *
     * @param carRecord
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "出入场查询-分页列表查询")
    @ApiOperation(value = "出入场查询-分页列表查询", notes = "出入场查询-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(CarRecord carRecord,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<CarRecord> queryWrapper = QueryGenerator.initQueryWrapper(carRecord, req.getParameterMap());
        queryWrapper.eq("leading_enterprise", 0);
        Page<CarRecord> page = new Page<CarRecord>(pageNo, pageSize);
        IPage<CarRecord> pageList = carRecordService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    @GetMapping(value = "/goodsList")
    public Result<?> goodsList(@RequestParam(name = "start") String start,
                               @RequestParam(name = "end") String end,
                               @RequestParam(name = "carType", required = false) String carType) {
        List<String> takeGoods = basicGoodsService.getTakeGoods();
        QueryWrapper<CarRecord> wrapper = new QueryWrapper<>();
        wrapper.select("goods", "COUNT(*) AS total",
                "SUM(CASE WHEN evn_type = '5' THEN 1 ELSE 0 END) AS guowu",
                "SUM(CASE WHEN evn_type = '6' THEN 1 ELSE 0 END) AS guoliu",
                "SUM(CASE WHEN evn_type = 'D' THEN 1 ELSE 0 END) AS xinnengyuan");
        wrapper.in("goods", takeGoods);
        wrapper.isNotNull("entry_time");
        wrapper.between("create_time", start, end);
        wrapper.like(StringUtils.isNotBlank(carType), "car_type", carType);
        wrapper.groupBy("goods");
        List<Map<String, Object>> maps = carRecordService.listMaps(wrapper);
        wrapper.clear();
        List<String> deliveryGoods = basicGoodsService.getDeliveryGoods();
        wrapper.select("goods", "COUNT(*) AS total",
                "SUM(CASE WHEN evn_type = '5' THEN 1 ELSE 0 END) AS guowu",
                "SUM(CASE WHEN evn_type = '6' THEN 1 ELSE 0 END) AS guoliu",
                "SUM(CASE WHEN evn_type = 'D' THEN 1 ELSE 0 END) AS xinnengyuan");
        wrapper.in("goods", deliveryGoods);
        wrapper.isNotNull("entry_time");
        wrapper.between("create_time", start, end);
        wrapper.like(StringUtils.isNotBlank(carType), "car_type", carType);
        wrapper.groupBy("goods");
        List<Map<String, Object>> maps1 = carRecordService.listMaps(wrapper);
        Map<String, List<Map<String, Object>>> map = new HashMap<>();
        map.put("take", maps);
        map.put("delivery", maps1);
        return Result.OK(map);
    }

    /**
     * 分页列表查询
     *
     * @param carRecord
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "出入场查询-分页列表查询")
    @ApiOperation(value = "出入场查询-分页列表查询", notes = "出入场查询-分页列表查询")
    @GetMapping(value = "/listLedger")
    public Result<?> listLedger(CarRecord carRecord,
                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                HttpServletRequest req) {
        carRecord.setPlateNo("*"+carRecord.getPlateNo()+"*");
        QueryWrapper<CarRecord> queryWrapper = QueryGenerator.initQueryWrapper(carRecord, req.getParameterMap());
        queryWrapper.eq("leading_enterprise", 0);
        queryWrapper.isNotNull("vin");
        Page<CarRecord> page = new Page<CarRecord>(pageNo, pageSize);
        IPage<CarRecord> pageList = carRecordService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    @AutoLog(value = "出入场查询-分页列表查询")
    @ApiOperation(value = "出入场查询-分页列表查询", notes = "出入场查询-分页列表查询")
    @GetMapping(value = "/oilList")
    public Result<?> oilList(CarRecord carRecord,
                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                HttpServletRequest req) {
        carRecord.setPlateNo("*"+carRecord.getPlateNo()+"*");
        QueryWrapper<CarRecord> queryWrapper = QueryGenerator.initQueryWrapper(carRecord, req.getParameterMap());
        queryWrapper.like("goods", "包装油").or().eq("goods", "包装辅材");
        Page<CarRecord> page = new Page<CarRecord>(pageNo, pageSize);
        IPage<CarRecord> pageList = carRecordService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * @param req
     * @return
     */
    @AutoLog(value = "出入场查询-统计")
    @ApiOperation(value = "出入场查询-统计", notes = "出入场查询-统计")
    @GetMapping(value = "/getCount")
    public Result<?> getCount(HttpServletRequest req) {
        List<Map<String, Object>> list = carRecordService.getCount();
        String[] date = new String[list.size()];
        int[] total = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            date[i] = list.get(i).get("time").toString();
            total[i] = Integer.parseInt(list.get(i).get("count").toString());
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("count", total);
        jsonObject.put("date", date);
        return Result.OK(jsonObject);
    }

    /**
     * @return
     */
    @AutoLog(value = "出入场查询-统计")
    @ApiOperation(value = "出入场查询-统计", notes = "出入场查询-统计")
    @GetMapping(value = "/getCountList")
    public Result<?> getCountList(@RequestParam(name = "start") String start,
                                  @RequestParam(name = "end") String end,
                                  @RequestParam(name = "goods", required = false) String goods,
                                  @RequestParam(name = "carType", required = false) String carType) {
        List<Map<String, Object>> list = carRecordService.getCountList(start,end,goods,carType);
        JSONObject jsonObject = new JSONObject();
        int total=0;
        for (Map<String, Object> map : list) {
            total+=Integer.parseInt(map.get("value").toString());
        }
        jsonObject.put("count", total);
        jsonObject.put("data", list);
        log.info("json: {}", jsonObject);
        return Result.OK(jsonObject);
    }

    /**
     * 添加
     *
     * @param carRecord
     * @return
     */
    @AutoLog(value = "出入场查询-添加")
    @ApiOperation(value = "出入场查询-添加", notes = "出入场查询-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody CarRecord carRecord) {
        carRecordService.save(carRecord);
        return Result.OK("添加成功！");
    }

    /**
     * 添加
     *
     * @param carRecord
     * @return
     */
    @AutoLog(value = "出入场查询-添加")
    @ApiOperation(value = "出入场查询-添加--对外", notes = "出入场查询-添加")
    @PostMapping(value = "/m/add")
    public Result<?> addM(@RequestBody CarRecord carRecord) {
        if (StringUtils.isNotEmpty(carRecord.getPlateNo())) {
            //进场
            if (carRecord.getExitTime() == null) {
                CarRegister lastByPlateNo = carRegisterService.getLastByPlateNo(carRecord.getPlateNo());
                if (lastByPlateNo != null) {
                    getCarRegister(carRecord, lastByPlateNo);
                    String path = convertBase64StrToImage(carRecord.getEntryPic());
                    carRecord.setEntryPic(path);
                    carRecordService.save(carRecord);
                    return Result.OK("添加成功！");
                }
                //出厂
            } else {
                LambdaQueryWrapper<CarRecord> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(CarRecord::getPlateNo, carRecord.getPlateNo());
                lambdaQueryWrapper.isNull(CarRecord::getExitTime).orderByDesc(CarRecord::getCreateTime);
                List<CarRecord> list = carRecordService.list(lambdaQueryWrapper);
                //没有入场记录
                if (list == null || list.isEmpty()) {
                    CarRegister lastByPlateNo = carRegisterService.getLastByPlateNo(carRecord.getPlateNo());
                    if (lastByPlateNo != null) {
                        getCarRegister(carRecord, lastByPlateNo);
                    }
                    String path = convertBase64StrToImage(carRecord.getExitPic());
                    carRecord.setExitPic(path);
                   carRecordService.save(carRecord);
                    return Result.OK("添加成功！");
                }
                //有入场记录
                CarRecord record = list.get(0);
                record.setExitTime(carRecord.getExitTime());
                String path = convertBase64StrToImage(carRecord.getExitPic());
                record.setExitPic(path);
                record.setBarrierGate1(carRecord.getBarrierGate1());
                carRecordService.updateById(record);
                return Result.OK("添加成功！");
            }

        }
        carRecordService.save(carRecord);
        return Result.OK("添加成功！");
    }

    private void getCarRegister(@RequestBody CarRecord carRecord, CarRegister carRegister) {
        carRecord.setEvnType(carRegister.getEvnType());
        carRecord.setPlateColor(carRegister.getPlateColor());
        carRecord.setVin(carRegister.getVin());
        carRecord.setEngineNum(carRegister.getEngineNum());
        carRecord.setLisense(carRegister.getLisense());
        carRecord.setInventory(carRegister.getInventory());
//        carRecord.setLeadingEnterprise(carRegister.getLeadingEnterprise());
        carRecord.setGoods(carRegister.getGoods());
        carRecord.setFreightVolume(carRegister.getFreightVolume());
        carRecord.setCarType(carRegister.getCarType());
    }

    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;

    /**
     * Base64字符串转图片
     *
     * @param base64String
     */
    public String convertBase64StrToImage(String base64String) {
        ByteArrayInputStream bais = null;
        try {
            //获取图片类型
            String suffix = "jpg";
            //获取JDK8里的解码器Base64.Decoder,将base64字符串转为字节数组
            byte[] bytes = Base64.getDecoder().decode(base64String);
            //构建字节数组输入流
            bais = new ByteArrayInputStream(bytes);
            //通过ImageIO把字节数组输入流转为BufferedImage
            BufferedImage bufferedImage = ImageIO.read(bais);
            //构建文件
            String sp = new SimpleDateFormat("yyyy_MM").format(new Date());
            sp = sp + File.separator + System.currentTimeMillis() + ".jpg";
            File imageFile = new File(uploadpath + File.separator + sp);
            if (!imageFile.exists()) {
                imageFile.mkdirs();// 创建文件根目录
            }
            //写入生成文件
            ImageIO.write(bufferedImage, suffix, imageFile);
            return sp;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bais != null) {
                    bais.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }


    /**
     * 编辑
     *
     * @param carRecord
     * @return
     */
    @AutoLog(value = "出入场查询-编辑")
    @ApiOperation(value = "出入场查询-编辑", notes = "出入场查询-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody CarRecord carRecord) {
        carRecordService.updateById(carRecord);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "出入场查询-通过id删除")
    @ApiOperation(value = "出入场查询-通过id删除", notes = "出入场查询-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        carRecordService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "出入场查询-批量删除")
    @ApiOperation(value = "出入场查询-批量删除", notes = "出入场查询-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.carRecordService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "出入场查询-通过id查询")
    @ApiOperation(value = "出入场查询-通过id查询", notes = "出入场查询-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        CarRecord carRecord = carRecordService.getById(id);
        if (carRecord == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(carRecord);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param carRecord
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CarRecord carRecord) {
        return super.exportXls(request, carRecord, CarRecord.class, "出入场查询");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CarRecord.class);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param carRecord
     */
    @RequestMapping(value = "/oilExportXls")
    public ModelAndView oilExportXls(HttpServletRequest request, CarRecord carRecord) {
        // Step.1 组装查询条件
        QueryWrapper<CarRecord> queryWrapper = QueryGenerator.initQueryWrapper(carRecord, request.getParameterMap());
        queryWrapper.like("goods", "包装油").or().eq("goods", "包装辅材");
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // Step.2 获取导出数据
        List<CarRecord> pageList = carRecordService.list(queryWrapper);
        List<CarRecord> exportList = null;

        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            exportList = pageList.stream().filter(item -> selectionList.contains(getId(item))).collect(Collectors.toList());
        } else {
            exportList = pageList;
        }

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "出入场查询"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, CarRecord.class);
        //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
        ExportParams  exportParams=new ExportParams("出入场查询" + "报表", "导出人:" + sysUser.getRealname(), "出入场查询");
        exportParams.setImageBasePath(upLoadPath);
        //update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
        mv.addObject(NormalExcelConstants.PARAMS,exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

    /**
     * 获取对象ID
     *
     * @return
     */
    private String getId(CarRecord item) {
        try {
            return PropertyUtils.getProperty(item, "id").toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @PostMapping("/bandLock")
    public Result<?> bandLock(@RequestParam(name = "lockCode") String lockCode,
                              @RequestBody CarRecord carRecord) {
        redisUtil.set(lockCode, carRecord.getId(), 0);
        return Result.OK("绑定成功", null);
    }

    @GetMapping("/m/all")
    public Result<?> mAll(@RequestParam(name = "start") String start,
                          @RequestParam(name = "end") String end) {
        LambdaQueryWrapper<CarRecord> wrapper = Wrappers.lambdaQuery();
        wrapper.between(CarRecord::getCreateTime, start, end);
        List<CarRecord> list = carRecordService.list(wrapper);
        return Result.OK(list);
    }

}
